<template>
  <div class="micro-goods-box">
    <div class="design-preview-controller">
      <div class="goods-list">
        <template v-if="formData.goods.length">

          <div v-if="formData.size!=1" class="Mall4j goods-box">
            <div v-for="num in 2" :key="key[num]" class="list">
              <div v-for="item in nGoods[num - 1]" :key="item.prodId" class="prod-item">
                <div class="distance" v-if="formData.showContent.find(x=>x===7)">7.6km</div>
                <div style="position: relative;">
                  <img v-if="item.pic" :src="item.pic" @error="item.pic = ''" class="prod-img" />
                  <img v-else src="@/assets/img/pc-micro-page/show-default.png" class="prod-img" />
                  <img v-if="item.status != 1" class="been_imgs" src="@/assets/img/pc-micro-page/been_shelves.png" >              
                </div>
                <div class="prod-info">
                  <div class="title">{{item.prodName}}</div>
                  <div class="store">{{item.shopName}}</div>
                  <div class="coupon" v-if="formData.showContent.find(x=>x===5) && item.couponList.length">
                    <!-- <div class="coupon-item">
                      <span class="right">满2件减10</span>
                    </div> -->
                    <div class="coupon-item" v-for="coupon in item.couponList" :key="coupon.couponId">
                      <span class="left">{{ $t('shopFeature.goods.couponL') }}</span>
                      <span class="right" v-if="coupon.couponType === 1">{{ $t('marketing.full') }}{{coupon.cashCondition}}{{ $t('marketing.reducea') }}{{coupon.reduceAmount}}</span>
                      <span class="right" v-else>{{ $t('marketing.full') }}{{coupon.cashCondition}}{{ $t('dataAnalysis.yuan') }}{{coupon.couponDiscount}}{{ $t('marketing.fold') }}</span>
                    </div>
                  </div>
                  <div class="price">
                    <div class="left">￥<span class="big">{{dealPrice(item.price)[0]}}</span><span class="small">.{{dealPrice(item.price)[1]}}</span></div>
                    <div class="right" v-if="formData.showContent.find(x=>x===6)">{{item.soldNum}}&nbsp;{{ $t('shopFeature.goods.payment') }}</div>
                  </div>
                  <div class="vip vip-zh-img" v-if="formData.showContent.find(x=>x===4)" :class="[vipImg]">
                    <div class="left" />
                    <div class="right">￥<span class="big">{{(item.price * 0.8).toFixed(2)}}</span></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 一列 -->
          <div v-else class="goods-box-one">
            <div v-for="(item, index) in formData.goods" :key="index" class="list">
              <img v-if="item.pic" :src="item.pic"  @error="item.pic = ''" class="prod-img" fit="fill" />
              <img v-else src="@/assets/img/pc-micro-page/show-default.png" class="prod-img" fit="fill" />
              <img v-if="item.status != 1" class="been_imgs" src="@/assets/img/pc-micro-page/been_shelves.png" >
              <div class="prod-info">
                <div>
                  <div class="title">{{item.prodName}}</div>
                  <div class="loc">
                    <div class="store">{{item.shopName}}</div>
                    <div class="distance" v-if="formData.showContent.find(x=>x===7)">7.6km</div>
                  </div>                  
                </div>
                <div class="coupon" v-if="formData.showContent.find(x=>x===5) && item.couponList.length">
                  <!-- <div class="coupon-item">
                    <span class="right">满2件减10</span>
                  </div> -->
                  <div class="coupon-item" v-for="coupon in item.couponList" :key="coupon.couponId">
                    <span class="left">{{ $t('shopFeature.goods.couponL') }}</span>
                    <span class="right" v-if="coupon.couponType === 1">{{ $t('marketing.full') }}{{coupon.cashCondition}}{{ $t('marketing.reducea') }}{{coupon.reduceAmount}}</span>
                    <span class="right" v-else>{{ $t('marketing.full') }}{{coupon.cashCondition}}{{ $t('dataAnalysis.yuan') }}{{coupon.couponDiscount}}{{ $t('marketing.fold') }}</span>
                  </div>
                </div>
                <div class="pay">
                  <div class="left">
                    <div class="price">￥<span class="big">{{dealPrice(item.price)[0]}}</span><span class="small">.{{dealPrice(item.price)[1]}}</span></div>
                    <div class="vip" v-if="formData.showContent.find(x=>x===4)" :class="[vipImg]">
                      <div class="left" />
                      <div class="right">￥<span class="big">{{(item.price * 0.8).toFixed(2)}}</span></div>
                    </div>
                  </div>
                  <div class="right" v-if="formData.showContent.find(x=>x===6)">{{item.soldNum}}{{ $t('shopFeature.goods.payment') }}</div>
                </div>
              </div>
            </div>
          </div>

        </template>
        
        <template v-else>
          <div class="goods-box default-goods-box"  v-if="formData.size!=1">
            <div v-for="item in goodsList" :key="item.prodId" class="prod-item default-prod-item">
              <img v-if="item.pic" :src="item.pic" @error="item.pic = ''" class="prod-img" />
              <img v-else src="@/assets/img/pc-micro-page/show-default.png" class="prod-img" />
              <div class="prod-info">
                <div class="title">{{item.prodName}}</div>
                <div class="price">
                  <div class="left">￥<span class="big">{{dealPrice(item.price)[0]}}</span><span class="small">.{{dealPrice(item.price)[1]}}</span></div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="goods-box-one">
            <div v-for="(item, index) in goodsList" :key="index" class="list">
              <img v-if="item.pic" :src="item.pic"  @error="item.pic = ''" class="prod-img default-prod-img" fit="fill" />
              <img v-else src="@/assets/img/pc-micro-page/show-default.png" class="prod-img" fit="fill" />
              <div class="prod-info">
                <div class="title">{{item.prodName}}</div>
                <div class="pay">
                  <div class="left">
                    <div class="price">￥<span class="big">{{dealPrice(item.price)[0]}}</span><span class="small">.{{dealPrice(item.price)[1]}}</span></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- <div class="empty-tips"
          v-else>
          {{$t('shopFeature.goods.pleaseAddProd')}}
        </div> -->
      </div>
    </div>

    <div v-if="isShowEdit"
         class="design-editor-item design-hide-class">
      <div class="design-config-editor">
        <div class="design-editor-component-title">{{$t('shopFeature.allCanUse.goodsList')}}</div>
        <!--选择商品-->
        <div class="design-editor-component-container">
          <el-form @submit.native.prevent  ref="formData" :model="formData" label-position="left" class="goods-select-form">
            <el-form-item :label="$i18n.t('shopFeature.goods.prod')" class="goods-select-con">
              <div class="goods-select-list">
                <div v-for="(item,index) in formData.goods"
                    :key="index"
                    class="goods-select-item">
                  <!-- <div class="goods-select-item-img"
                      :class="{'goods-empty': !formData.goods[0].prodId}"
                      :style="{backgroundImage:'url('+(item.pic || defImg)+')'}"></div> -->
                  <el-image class="goods-select-item-img" :class="{'goods-empty': !formData.goods[0].prodId}"
                  :src="item.pic" fit="fill">
                      <div slot="error" class="image-slot">
                          <img src="@/assets/img/pc-micro-page/show-default.png" fit="fill">
                      </div>
                  </el-image>
                  <span class="close-item"
                        @click="formData.goods.splice(index,1);carding()">x</span>
                </div>
                <div class="goods-select-item">
                  <div class="goods-select-item-img add-btn"
                      @click="selectProdHandle">
                      <i class="el-icon-plus"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="$i18n.t('shopFeature.goods.listStyle')">
              <el-radio-group v-model="formData.size" @change="changeSize">
                <el-radio v-for="(count, index) in lineSize" :label="count.value" :key="index">{{count.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$i18n.t('shopFeature.goods.showContent')" class="goods-show-container">
              <div class="goods-show-content">
              <el-checkbox-group v-model="formData.showContent">
                <el-checkbox v-for="(showItem, index) in goodsShowContent" :disabled="index === 0 || index === 1 || index === 2" :key="index" :label="showItem.value">{{showItem.label}}</el-checkbox>
              </el-checkbox-group>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <prods-select
      v-if="dialogChooseGoods"
      ref="ProdsSelect"
      @refreshSelectProds="chooseGoodsFun">
    </prods-select>
     <!-- 商品 | 页面 | 跳转链接弹窗 start -->
     <decorate-dialog-select
      :dialogVisible="dialogVisible"
      :deviceType="'mobile'"
      :isMulilt="true"
      :echoDataList="echoDataList"
      :currentSelectType="[1]"
      @handleClose="handleDialogClose"
      @handleDialogSubmit="handleDialogSubmit">
    </decorate-dialog-select>
    <!-- 商品 | 页面 | 跳转链接弹窗 end -->
  </div>
</template>
<script>
/**
 * 创建新组件之后，在all-can-use-components中添加
 * 必须应用 microCreateMinis
 * 数据必须以formData包含
 * */
import { microCreateMinis } from '../../minis'
import ProdsSelect from '@/components/prods-select'
import decorateDialogSelect from '@/components/decorateDialogSelect/index.vue' // 选择商品
/** 商品组件 */
export default {
  name: 'micro-goods-box',
  mixins: [microCreateMinis],
  data () {
    return {
      lang: window.localStorage.getItem('o2oLang'), // 语言
      commonCheckFieldRules: 'checkData', // 当前组件默认的规则判断函数
      dialogChooseGoods: false,
      isGetChooseData: false, // 是否该是获取选择的数据
      formData: {
        size: 2, // 一行多少个
        showContent: [1, 2, 3],
        goods: []
        // buy_btn_type: 1, // 购买按钮的样式
        // button_text: '马上抢'// 购买按钮的文本
      },
      key: ['list1', 'list2'],
      nGoods: [],
      // 商品显示内容
      goodsShowContent: [
        {
          value: 1,
          label: this.$i18n.t('shopFeature.goods.prodName')
        },
        {
          value: 2,
          label: this.$i18n.t('shopFeature.goods.prodPrice')
        },
        {
          value: 3,
          label: this.$i18n.t('shopFeature.goods.storeName')
        },
        {
          value: 4,
          label: this.$i18n.t('shopFeature.goods.memberPrice')
        },
        {
          value: 5,
          label: this.$i18n.t('shopFeature.goods.coupon')
        },
        {
          value: 6,
          label: this.$i18n.t('shopFeature.goods.sales')
        },
        {
          value: 7,
          label: this.$i18n.t('shopFeature.goods.distance')
        }],
      // 一行几个
      lineSize: [
        {
          value: 1,
          label: this.$i18n.t('shopFeature.goods.oneLineItem1')
        },
        {
          value: 2,
          label: this.$i18n.t('shopFeature.goods.oneLineItem2')
        }
      ],
      // 获取的接口数据
      goodsList: [],
      // 默认数据
      demoGoods: [],
      dialogVisible: false, // 商品弹窗
      echoDataList: [] // 回显商品数据
    }
  },
  props: {
    current: {
      type: Number
    }
  },
  watch: {
    goodsList: {
      deep: true,
      handler (val) {
        if (val.length) {
          if (!this.goodsList.find(x => x.myGoodsType === 1)) {
            this.formData.goods = []
            val.map(res => {
              this.formData.goods.push(res.prodId)
            })
            this.goodsList.concat(val)
          } else {

          }
        } else {
          this.goodsList = this.demoGoods
        }
      }
    }
  },
  filters: {
    buy_btn_type (val) { // 标题
      let str = ''
      switch (val) {
        case 6:
          str = 'danger'
          break
        case 8:
          str = 'danger'
          break
      }
      return str
    }
  },
  components: {
    ProdsSelect,
    decorateDialogSelect
  },
  computed: {
    theme () {
      return this.$store.getters.theme
    },
    vipImg () {
      return this.lang === 'en' ? 'vip-en-img' : 'vip-zh-img'
    }
  },
  mounted () {
    this.goodsList = []
    for (let i = 0; i < 4; i++) {
      this.goodsList.push({
        prodId: '', // 商品id
        prodName: this.$i18n.t('shopFeature.goods.prodName'),
        price: '90', // 商品价格
        pic: require('@/assets/img/micro-page/def.png'),
        brief: this.$i18n.t('shopFeature.goods.prodDesc'),
        myGoodsType: 1
      })
    }
    this.carding()
  },
  methods: {
    // 选择商品操作
    selectProdHandle () {
      this.dialogVisible = true
      this.echoDataList = [] // 商品数据回显
      this.formData.goods.forEach(item => {
        this.echoDataList.push(item)
      })
    },
    // 选择商品回调
    chooseGoodsFun ($event) {
      if ($event) {
        if (this.goodsList.find(x => x.myGoodsType === 1)) {
          this.goodsList = []
        }
        $event.map(newGoodItem => {
          if (this.formData.goods.indexOf(newGoodItem.prodId) === -1) {
            this.goodsList.push(newGoodItem)
          }
        })
      }
      this.dialogChooseGoods = false
    },
    /** 批量获取商品详情 */
    getGoodsInfo (prodIds, prodType) {
      this.$http({
        url: this.$http.adornUrl('/search/renovationPage'),
        method: 'get',
        params: this.$http.adornParams({
          prodIds,
          prodType
        })
      }).then(({ data }) => {
        this.goodsList = this.sortList(data)
        this.goodsList.forEach(item => {
          if (!item.pic.includes('http')) {
            item.pic = process.env.VUE_APP_RESOURCES_URL + item.pic
          }
        })
      })
    },
    /**
     * 按照添加的顺序排序
     */
    sortList (goodsList) {
      let showArr = this.dataField.goods
      goodsList.forEach(item => {
        item.sortId = showArr.indexOf(item.prodId)
      })
      return goodsList.sort((a, b) => { return a.sortId - b.sortId })
    },
    // 关闭弹窗
    handleDialogClose () {
      this.dialogVisible = false
    },
    // 商品确定
    handleDialogSubmit ({ type, value }) {
      if (type === '1') {
        this.formData.goods = []
        value.goodsItem.forEach(item => {
          let couponList = []
          if (item.couponList) {
            couponList = item.couponList.map(x => {
              return {
                couponId: x.couponId,
                couponType: x.couponType,
                cashCondition: x.cashCondition,
                reduceAmount: x.reduceAmount,
                couponDiscount: x.couponDiscount
              }
            })
          }
          this.formData.goods.push({
            prodId: item.prodId, // 商品id
            shopId: item.shopId, // 店铺id
            prodType: item.prodType, // 商品类型
            prodName: item.prodName, // 商品名称
            status: item.status, // 商品状态
            price: item.price, // 商品价格
            pic: item.pic, // 商品图片
            brief: item.brief, // 商品描述
            // memberPrice: item.memberPrice, // 会员价
            soldNum: item.soldNum, // 销量
            couponList: couponList.slice(0, 1), // 优惠券
            shopName: item.shopName
          })
        })
      }
      this.carding()
      this.dialogVisible = false
    },
    // 梳理数据
    carding () {
      const dataField = this.formData
      if (dataField.size === 2) {
        // 一行两个
        const list = dataField.goods
        var leftList = []
        var rightList = []
        list.forEach((item, index) => {
          if ((index) % 2 === 0) {
            leftList.push(item)
          } else {
            rightList.push(item)
          }
        })
        this.nGoods = [leftList, rightList]
      }
    },
    // 修改显示数量
    changeSize () {
      if (this.formData.size === 2) {
        this.carding()
      } else {
        this.nGoods = []
      }
    },
    dealPrice (val) {
      if (val.toString().indexOf('.') > -1) {
        return val.toString().split('.')
      } else {
        return [val, '00']
      }
    },
    /* 校验 */
    checkData () {
      if (this.formData.goods.length > 0) {
        this.myCheckResult(true)
      } else {
        this.$newMessage.error(this.$i18n.t('shopFeature.allCanUse.goodsList') + this.current + this.$i18n.t('shopFeature.goods.pleaseAddProd'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
